package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Random;

/**
 * @author 嘉德罗斯
 * @date 2021/11/8
 */
@DubboService
public class VoiceImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public void save(Voice voice) {
        voice.setVeId(idWorker.getNextId("veId"));
        mongoTemplate.save(voice);
    }

    @Override
    public Voice find(Long userId) {
        Random random = new Random();
        Query query = Query.query(Criteria.where("userId").ne(userId));

        List<Voice> voices = mongoTemplate.find(query, Voice.class);
        int a  = random.nextInt(voices.size());

        Query query1 = query.skip(a).limit(1);
        Voice voice = mongoTemplate.findOne(query1, Voice.class);
        mongoTemplate.remove(voice);
        return voice;
    }
}
